/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2022-05-30 12:10:47
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-10 10:08:26
 */
// 封装axios
import { Toast } from 'antd-mobile'
import axios from 'axios'
import { getToken } from '@/utils/storage'
// import { Token } from '@/types/data'
import history from '@/utils/history'
import store from '@/store'
import { saveToken, logout } from '@/store/actions/login'
const instance = axios.create({
  // baseURL: 'http://geek.itheima.net/v1_0/',
  baseURL: 'http://toutiao.itheima.net/v1_0/',
  // timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken().token
    // console.log(token, 1)

    if (token) {
      config.headers!.Authorization = 'Bearer ' + token
      // 错误
      // config.headers?.Authorization = `Bearer ${token}`

      // 正确
      // if (config.headers) {
      //   config.headers.Authorization = `Bearer ${token}`
      // }
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error) {
    // 对请求错误做些什么
    if (!error.response) {
      Toast.show('网络异常')
      return Promise.reject(error)
    }
    if (error.response.status !== 401) {
      Toast.show('后端错误')
      return Promise.reject(error)
    }
    // eslint-disable-next-line camelcase
    const { refresh_token } = getToken()
    // console.log(qq, 3)
    // eslint-disable-next-line camelcase
    /* 不存在刷新token */
    // eslint-disable-next-line camelcase
    if (!refresh_token) {
      // alert('refresh_token')
      history.replace('/login', { from: history.location.pathname })
      Toast.show('登录信息过期')
      return Promise.reject(error)
    }
    /* 存在刷新token */
    try {
      // 使用refresh_token去换取新token
      // 使用 axios 来发送请求
      const res = await axios.put('http://geek.itheima.net/v1_0/authorizations', null, {
        headers: {
          // eslint-disable-next-line camelcase
          Authorization: `Bearer ${refresh_token}`
        }
      })
      // setToken(tokens)
      // eslint-disable-next-line camelcase
      store.dispatch(saveToken({ token: res.data.data.token, refresh_token }))

      return instance(error.config)
    } catch (err) {
      // setToken(tokens)
      store.dispatch(logout())
      history.replace('/login', { from: history.location.pathname })
      return Promise.reject(error)
    }
  }
)

export default instance
